﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SPAzureBlobField.Services;
using Microsoft.WindowsAzure;
using Microsoft.SharePoint;
using Microsoft.WindowsAzure.StorageClient;

namespace SPAzureBlobField.Classes
{
    public class AzureStorageManager
    {
        public void SetSharedAccessSignatureForBlob(Blob blob)
        {
            SPSite site = new SPSite(blob.SiteId, SPContext.Current.Web.CurrentUser.UserToken);
            SPWeb web = site.OpenWeb(blob.WebId);
            SPList list = web.Lists[blob.ListId];
            SPListItem listItem = list.GetItemById(blob.ItemId);
            SPAzureBlobField field = listItem.Fields[blob.FieldId] as SPAzureBlobField;

            var cloudStorageAccountWithLocalValues = new CloudStorageAccount(
                new StorageCredentialsAccountAndKey(field.AzureAccountName, field.AzureAccountKey), true);
            CloudBlobClient cloudBlobClient = cloudStorageAccountWithLocalValues.CreateCloudBlobClient();

            // Accessing blob in Azure Storage.
            var blobContainer = cloudBlobClient.GetContainerReference(field.AzureAccountBlobContainer);

            if (blob.IsUpload)
            {
                // Getting the SAS for the container (need to share the container to create a new item in it) !!
                string sasContainer = blobContainer.GetSharedAccessSignature(GetSharedAccessPolicy(true, false));
                blob.SharedAccessSignature = new UriBuilder(blobContainer.Uri) { Query = sasContainer.TrimStart('?') }.Uri.AbsoluteUri;
            }
            else
            {
                var blobReference = blobContainer.GetBlobReference(blob.BlobId);
                string sasBlob = blobReference.GetSharedAccessSignature(GetSharedAccessPolicy(false, false));
                blob.SharedAccessSignature = new UriBuilder(blobContainer.Uri) { Query = sasBlob.TrimStart('?') }.Uri.AbsoluteUri;
            }

            // Disposing SP Objects.
            web.Dispose();
            site.Dispose();
        }

        public static void CreateSilverlightPolicy(string azureAccountName, string azureAccountKey)
        {
            var cloudStorageAccountWithLocalValues = new CloudStorageAccount(
                new StorageCredentialsAccountAndKey(azureAccountName, azureAccountKey), true);
            CloudBlobClient cloudBlobClient = cloudStorageAccountWithLocalValues.CreateCloudBlobClient();

            cloudBlobClient.GetContainerReference("$root").CreateIfNotExist();
            cloudBlobClient.GetContainerReference("$root").SetPermissions(
                new BlobContainerPermissions()
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });
            var blob = cloudBlobClient.GetBlobReference("clientaccesspolicy.xml");
            blob.Properties.ContentType = "text/xml";
            blob.UploadText(@"<?xml version=""1.0"" encoding=""utf-8""?>
                    <access-policy>
                      <cross-domain-access>
                        <policy>
                          <allow-from http-methods=""*"" http-request-headers=""*"">
                            <domain uri=""*"" />
                            <domain uri=""http://*"" />
                          </allow-from>
                          <grant-to>
                            <resource path=""/"" include-subpaths=""true"" />
                          </grant-to>
                        </policy>
                      </cross-domain-access>
                    </access-policy>");
        }

        public static string GetTempUrlForContent(Blob blob)
        {
            SPSite site = new SPSite(blob.SiteId, SPContext.Current.Web.CurrentUser.UserToken);
            SPWeb web = site.OpenWeb(blob.WebId);
            SPList list = web.Lists[blob.ListId];
            SPListItem listItem = list.GetItemById(blob.ItemId);
            SPAzureBlobField field = listItem.Fields[blob.FieldId] as SPAzureBlobField;

            var cloudStorageAccountWithLocalValues = new CloudStorageAccount(
                new StorageCredentialsAccountAndKey(field.AzureAccountName, field.AzureAccountKey), true);
            CloudBlobClient cloudBlobClient = cloudStorageAccountWithLocalValues.CreateCloudBlobClient();

            // Accessing blob in Azure Storage.
            var blobContainer = cloudBlobClient.GetContainerReference(field.AzureAccountBlobContainer);
            var blobReference = blobContainer.GetBlobReference(blob.BlobId);

            string sasBlob = blobReference.GetSharedAccessSignature(GetSharedAccessPolicy(false, false));
            blob.SharedAccessSignature = new UriBuilder(blobContainer.Uri) { Query = sasBlob.TrimStart('?') }.Uri.AbsoluteUri;

            // Disposing SP Objects.
            web.Dispose();
            site.Dispose();

            return sasBlob;
        }

        private static SharedAccessPolicy GetSharedAccessPolicy(bool isUpload, bool shareToExternal)
        {
            var accessPolicy = new SharedAccessPolicy();
            if (shareToExternal)
                accessPolicy.SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromDays(1);
            else
                accessPolicy.SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromMinutes(30);

            if (isUpload)
                accessPolicy.Permissions = SharedAccessPermissions.Write;
            else
                accessPolicy.Permissions = SharedAccessPermissions.Read;

            return accessPolicy;
        }
    }
}